package com.jadows.tdog.service.impl;

import com.jadows.tdog.domain.ChatRoom;
import com.jadows.tdog.exception.ServiceException;
import com.jadows.tdog.repository.ChatRoomRepository;
import com.jadows.tdog.service.ChatRoomService;
import com.jadows.tdog.util.IdUtils;
import com.jadows.tdog.util.SecurityUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

/**
 * @author taojiacheng
 */
@Service
@RequiredArgsConstructor
public class ChatRoomServiceImpl implements ChatRoomService {

    final ChatRoomRepository chatRoomRepository;

    @Override
    public ChatRoom createRoom(Set<String> targetUserIds) {
        String self = SecurityUtil.getCurrentUser().getMemberId();
        targetUserIds.add(self);
        ChatRoom chatRoom = new ChatRoom()
                .setRoomId(IdUtils.nextId())
                .setCreatorId(SecurityUtil.getCurrentUser().getMemberId())
                .setRoomName(SecurityUtil.getCurrentUser().getMemberId())
                .setMemberIds(targetUserIds)
                .setCreateTime(new Date());
        chatRoomRepository.save(chatRoom);
        return chatRoom;
    }

    @Override
    public Set<String> getRoomMembers(Long roomId) {
        // 根据群聊的 ID 在数据库中查找相应的群聊实体
        ChatRoom chatRoom = chatRoomRepository.findById(roomId)
                .orElseThrow(() -> new ServiceException("Chat room not found"));
        // 返回群聊的成员列表
        return chatRoom.getMemberIds();
    }

    @Override
    public Set<ChatRoom> listRooms() {
        String uid = SecurityUtil.getCurrentUser().getMemberId();
        return chatRoomRepository.findAllByMemberIdsContains(uid);
    }
}
